package at.codebase.web.servlets.user;

import static at.codebase.web.util.i18n.I18NFactory.i18n;

import java.util.ArrayList;
import java.util.List;

import at.codebase.core.log.Log;
import at.codebase.db.dao.EImageDao;
import at.codebase.db.dao.EItemDao;
import at.codebase.db.dao.EItemFeedbackDao;
import at.codebase.db.dao.EMessageDao;
import at.codebase.db.dao.EUserDao;
import at.codebase.db.entities.EImage;
import at.codebase.db.entities.EItem;
import at.codebase.db.entities.EItemFeedback;
import at.codebase.db.entities.EMessage;
import at.codebase.db.entities.EUser;
import at.codebase.web.templates.MainTemplate;
import at.codebase.web.templates.UserProfileTemplate;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

import com.google.appengine.api.users.UserServiceFactory;

public class UserDelete extends AUserProfile {
	
	@Override
	void buildUserPage(MainTemplate mainTemplate, UserProfileTemplate userProfileTemplate, RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		EUser user = requestInfo.getUser();
		if(user != null){
			if(requestType.equals(RequestType.GET)){
				buildPage(mainTemplate, userProfileTemplate, requestInfo);
			}else{
				try {
					String randomKeyInput = requestInfo.getParameters().getString("randomKey");
					if(useToken(randomKeyInput)){
						//DELETE ACCOUNT
						AccountDeleteHelper.delete(user);
						Log.logUser(requestInfo.getUser().getId(),
								"User (userId=" + user.getId() + ", googleId="
										+ user.getGoogleUserId()
										+ ") deleted his account");
					
						redirectTo(UserServiceFactory.getUserService().createLogoutURL("/newest"));	
					}else{
						buildPage(mainTemplate, userProfileTemplate, requestInfo);
					}

				} catch (ParameterDoesNotExistException e) {
					buildPage(mainTemplate, userProfileTemplate, requestInfo);
				}
			}
		
		}
	}
	
	private void buildPage(MainTemplate mainTemplate, UserProfileTemplate userProfileTemplate, RequestInformation requestInfo) {
		mainTemplate.setTitle(i18n(requestInfo.getLocale()).string("userDelete_header"));
		Template userDeleteT = TemplateEngine.getTemplate("user/site_profile_delete.html");
		userDeleteT.setText("randomKey", nextToken());
		userProfileTemplate.setContent(userDeleteT);
	}
	
	public static class AccountDeleteHelper {
		
		public static void delete(EUser user){
			//Delete work order:
			//EImage.uploader == user 
				//Also delete the ref of the items
			//EItem.seller == user
			//EMessage.addressor == user
			//EMessage.recipient == user
			//EItemFeedback.author == user
			//EUser == user (finally)

			/**
			 * IMAGES
			 */
			ArrayList<EImage> imageList = EImageDao.getImageByUploader(user.getId());
			ArrayList<Long> imageIds = new ArrayList<Long>();
			for(EImage image:imageList){
				if(image != null){
					EItem item = EItemDao.getItemById(image.getImageId());
					if(item != null)
						item.getImageKeys().remove(EImage.key(image.getId()));
					imageIds.add(image.getId());
				}
			}
			EImageDao.removeImageByIds(imageIds);
			
			/**
			 * ITEMS
			 */
			ArrayList<EItem> itemList = EItemDao.getItemsBySeller(user.getId());
			ArrayList<Long> itemIds = new ArrayList<Long>();
			for(EItem item:itemList){
				if(item != null){
					itemIds.add(item.getId());
				}
			}
			EItemDao.removeItemsById(itemIds);
			
			/**
			 * MESSAGES
			 */
			List<EMessage> messagesByAddressor = EMessageDao.getMessagesByAddressor(user.getId());
			List<EMessage> messagesByRecipient = EMessageDao.getMessagesByRecipient(user.getId());
			ArrayList<Long> messageIds = new ArrayList<Long>();
			for(EMessage message:messagesByAddressor){
				if(message != null){
					messageIds.add(message.getId());
				}
			}
			for(EMessage message:messagesByRecipient){
				if(message != null){
					messageIds.add(message.getId());
				}
			}
			EMessageDao.removeMessagesById(messageIds);
			
			/**
			 * ITEM FEEDBACKS
			 */
			ArrayList<EItemFeedback> feedbackByAuthor = EItemFeedbackDao.getFeedbackByAuthor(user.getId());
			ArrayList<Long> feedbackIds = new ArrayList<Long>();
			for(EItemFeedback feedback:feedbackByAuthor){
				if(feedback != null){
					feedbackIds.add(feedback.getId());
				}
			}		
			EItemFeedbackDao.removeItemFeedbacksById(feedbackIds);
			
			/**
			 * USER
			 */
			EUserDao.removeUser(user);
			/*
			System.out.println("Images: ");
			ArrayList<EImage> imageList = EImageDao.getImageByUploader(user.getId());
			for(EImage image:imageList){
				System.out.println(image);
			}
			System.out.println();
			
			System.out.println("Items: ");
			ArrayList<EItem> itemList = EItemDao.getItemsBySeller(user.getId());
			for(EItem item:itemList){
				System.out.println(item);
			}
			System.out.println();
			
			System.out.println("Messages (send): ");
			List<EMessage> messagesByAddressor = EMessageDao.getMessagesByAddressor(user.getId());
			for(EMessage message:messagesByAddressor){
				System.out.println(message);
			}
			System.out.println();
			
			System.out.println("Messages (resieved): ");
			List<EMessage> messagesByRecipient = EMessageDao.getMessagesByRecipient(user.getId());
			for(EMessage message:messagesByRecipient){
				System.out.println(message);
			}
			System.out.println();
			
			
			System.out.println("Feedback: ");
			ArrayList<EItemFeedback> feedbackByAuthor = EItemFeedbackDao.getFeedbackByAuthor(user.getId());
			for(EItemFeedback feedback:feedbackByAuthor){
				System.out.println(feedback);
			}
			System.out.println();
			*/
			
		}
		
	}

}